package com.chery.media.ui.main.home

import androidx.lifecycle.LifecycleOwner
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.chery.media.R
import com.chery.media.contacts.CommonContacts
import com.chery.media.contacts.StorageContacts
import com.chery.media.helper.LocationHelper
import com.chery.media.library.base.BaseViewModel
import com.chery.media.library.event.SingleLiveEvent
import com.chery.media.library.extend.asResponse
import com.chery.media.library.extend.getStorageInt
import com.chery.media.library.extend.getStorageString
import com.chery.media.library.extend.jsonToList
import com.chery.media.library.extend.livedata.StringLiveData
import com.chery.media.library.extend.toDrawable
import com.chery.media.library.extend.toResString
import com.chery.media.library.extend.toTime13String
import com.chery.media.library.extend.toast
import com.chery.media.library.network.ResponseThrowable
import com.chery.media.network.model.AppInfoBean
import com.chery.media.network.model.BannerBean
import com.chery.media.network.model.WeatherBean
import com.chery.media.utils.appRepository
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.launch
import okhttp3.OkHttpClient

class HomeViewModel : BaseViewModel() {

    val appInstall = arrayListOf<AppInfoBean>()

    val WeatherTime = 10 * 60 * 1000L

    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
        val currentWeatherJson = getStorageString(StorageContacts.CURRENT_WEATHER)
        if (currentWeatherJson.isNullOrEmpty().not()) {
            val weather = GsonUtils.fromJson(currentWeatherJson, WeatherBean::class.java)
            currentWeather.postValue(weather)
        }
        val bannerJson = getStorageString(StorageContacts.BANNER_DATA)
        if (bannerJson.isNullOrEmpty().not()) {
            val banner = GsonUtils.fromJson(bannerJson, BannerBean::class.java)
            bannerData.postValue(banner)
        }
        getWeather()
        getBannerData()
    }

    // banner数据
    val bannerData = SingleLiveEvent<BannerBean>()

    val currentWeather = SingleLiveEvent<WeatherBean>()

    var isContinue = true

    private var codeJob: Job? = null

    fun getWeather() {
        codeJob = CoroutineScope(Dispatchers.Main + SupervisorJob()).launch {
            do {
                getCurrentWeather()
                delay(WeatherTime)
            } while (isContinue)
        }
    }

    override fun onCleared() {
        super.onCleared()
        isContinue = false
        codeJob?.cancel()
    }


    // 获取当前天气
    private fun getCurrentWeather(lat: String = LocationHelper.latitude, lon: String = LocationHelper.longitude){
        val client = OkHttpClient()
        val request = okhttp3.Request.Builder().get()
            .url("https://api.openweathermap.org/data/2.5/weather?lat=${lat}&units=metric&lon=${lon}&appid=${CommonContacts.WEATHER_APPID}&lang=${getCurrentLanguage()}")
            .build()
        val response = client.newCall(request)
        response.enqueue(object : okhttp3.Callback {
            override fun onFailure(call: okhttp3.Call, e: java.io.IOException) {
                LogUtils.e("天气数据=====", e.message)
            }

            override fun onResponse(call: okhttp3.Call, response: okhttp3.Response) {
                val weatherJSON = response.body?.string()
                LogUtils.e("天气数据=====", weatherJSON)
                val weather = GsonUtils.fromJson(weatherJSON, WeatherBean::class.java)
                currentWeather.postValue(weather)
            }
        })
    }

    private fun getCurrentLanguage(): String {
        return  when (getStorageInt(StorageContacts.CURRENT_LANGUAGE)) {
            1 -> "en"  // 英语
            2 -> "zh_cn" // 中文
            3 -> "ru" // 俄语
            4 -> "uz" //乌兹别克语
            else -> "zh_cn"
        }
    }

    // 获取banner数据
    fun getBannerData() {
        val map = mutableMapOf<String, Any>()
        map["limit"] = "10"
        map["page"] = "1"
        launch {
            appRepository.getBannerData(map)
                .asResponse()
                .catch {  if (it is ResponseThrowable) it.errMsg.toast() }
                .collect {
                    bannerData.postValue(it)
                }
        }
    }

}